package com.dbcs.servlets;

import java.io.IOException;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.dbcs.beans.Cliente;
import com.dbcs.persistencia.DAOCliente;
import com.dbcs.utilidades.LeerPropiedades;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/ServletLoggin")
public class ServletLoggin extends HttpServlet {
	
	Logger logger = Logger.getLogger("ServletLoggin.class");
	private static final long serialVersionUID = 1L;
	private static Properties propiedades = new LeerPropiedades().getProperties();
	private static final String URL_MAIN = propiedades.getProperty("URL_MAIN");
	private static final String URL_LOGGIN = propiedades.getProperty("URL_LOGGIN");
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletLoggin() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String loggin = request.getParameter("loggin");
		String pass = request.getParameter("password");
		
		String url = "";
		
		
		try {
			DAOCliente d = new DAOCliente();
			
			Cliente c = d.compruebaCliente(loggin, pass);
			
			if (c == null){
				url = URL_LOGGIN;
			}else{
				request.getSession().setAttribute("cliente", c);
				url = URL_MAIN;
			}
			
		} catch (Exception e) {
			
			logger.error("ERROR: "+e);
			
			url = URL_LOGGIN;
		} 
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		
		dispatcher.forward(request, response);
		
		
	}

}
